package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    /**
     * 菜品管理
     */
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据条件查询分页数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "菜品分页查询")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name ="page" ,value = "页码",readOnly = true),
                    @ApiImplicitParam(name = "pageSize",value = "当前页条目数",readOnly = true),
                    @ApiImplicitParam(name = "name",value = "查询条件",readOnly = true)
            }
    )
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造条件构造器对象
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(dishPage, queryWrapper);
        //对象拷贝 分页参数 将基本信息从dish 放到dishdto中
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //获取查询到信息集合
        List<Dish> records = dishPage.getRecords();//   List<Dish>

        List<DishDto> list = records.stream().map((item) -> {//item->dish
            //item  为 每一个 dish
            DishDto dishDto = new DishDto();
            //dish基本字段复制
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                //赋值
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;//基本字段+categoryName
        }).collect(Collectors.toList());//每一个元素dishDto
        //set赋值 数据赋值 list 放到page对象里
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);//res.data.records(dishDto多个)
    }

    /**
     * 保存菜品信息
     *
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "保存菜品信息")

    @ApiImplicitParam(name = "dishDto", value = "菜品及口味信息", readOnly = true)


    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理所有菜品的缓存信息
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//清理某个分类下面的菜品缓存数据
        String keys = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);

        return R.success("菜品添加成功");
    }

    /**
     * 根据id查询菜品及口味数据
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询菜品合口味")

    @ApiImplicitParam(name = "id", value = "菜品id", readOnly = true)
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品和口味数据
     *
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "修改菜品")

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存信息
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//清理某个分类下面的菜品缓存数据
        String keys = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);

        return R.success("修改菜品成功");
    }

    /**
     * 批量删除菜品及口味
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除")

    @ApiImplicitParam(name = "ids", value = "多菜品id", readOnly = true)


    @DeleteMapping
    public R<String> deleteByIds(@RequestParam Long[] ids) {
        List<Long> list = new ArrayList<>(Arrays.asList(ids));
        //根据ids查询出菜品
        List<Dish> dishes = dishService.listByIds(list);
        //跟据菜品id查询对应口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishes);
        List<DishFlavor> list1 = dishFlavorService.list(queryWrapper);
        dishFlavorService.removeByIds(list1);
        //删除菜品
        dishService.removeByIds(list);

        return R.success("删除成功");
    }

    /**
     * 批量停售
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量停售")
    @ApiImplicitParam(name = "ids", value = "多菜品id", readOnly = true)
    @PostMapping("/status/0")
    public R<String> statusUpdate0(@RequestParam Long[] ids) {
        //遍历数组获取id
        for (Long id : ids) {
            //根据id获取菜品
            Dish dish = dishService.getById(id);
            //将状态设置为0停售
            dish.setStatus(0);
            //将数据更新到数据库
            dishService.updateById(dish);
        }
//        返回更新成功标志
        return R.success("商品已停售");
    }

    /**
     * 批量起售
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量起售")

    @ApiImplicitParam(name = "ids", value = "多菜品id", readOnly = true)


    @PostMapping("/status/1")
    public R<String> statusUpdate1(@RequestParam Long[] ids) {
        //遍历数组获取id
        for (Long id : ids) {
            //根据id获取菜品
            Dish dish = dishService.getById(id);
            //将状态设置为0启售
            dish.setStatus(1);
            //将数据更新到数据库
            dishService.updateById(dish);
        }
//        返回更新成功标志
        return R.success("商品已启售");
    }

    /**
     * 根据分类id查询菜品
     *
     * @param dish
     * @return
     */
    @ApiOperation(value = "查询单个菜品")
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            //如果存在直接返回无序查询数据库
            return R.success(dishDtos);
        }
        //根据传输的分类id查询菜品名称
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = dishService.list(queryWrapper);
        dishDtos = dishes.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //先将基本信息拷贝到dto里
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);//把口味放到flavors
            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的数据缓存到数据库
        redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }


}
